package common;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Marshall {
	
	public static String getValue(String tag, String message){
		Document doc=null;
		try{
			doc = DocumentHelper.parseText(message);
		}
		catch(DocumentException de){
			de.printStackTrace();
		}
		Element root = doc.getRootElement();
		return root.element(tag).getText();
	}
	
	public static String putTag(String  message,  String tag, String value){
		DocumentFactory DocumentFactory = new DocumentFactory();
		Document doc=null;
		Element root;
		if ( message != null){
			try{
				doc = DocumentHelper.parseText(message);
			}
			catch(DocumentException de){
				de.printStackTrace();
			}
			root = doc.getRootElement();
			Element newElement = DocumentFactory.createElement(tag);
			newElement.setText(value);
			root.add(newElement);
		}else{
			doc = DocumentHelper.createDocument();
			root = doc.addElement("message");
			Element newElement = root.addElement(tag);
			newElement.setText(value);
		}		
		return root.asXML();
	}

	
	public static void main(String args[]){
		String str = Marshall.putTag(null, "name", "clinton");
		System.out.println(str);
		String str2 = Marshall.putTag(str, "age", "18");
		System.out.println(str2);
		String value = Marshall.getValue("age", str2);
		System.out.println(value);
	}
	
}
